import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown, Menu } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule } from './service';

import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
interface TableListProps extends FormComponentProps {}


const TableList: React.FC<TableListProps> = () => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);

    const actionRef = useRef<ActionType>();

    // 列定义
    const columns: ProColumns<TableListItem>[] = [
        {
            title: formatMessage({ id: 'app.base.name' }),
            dataIndex: 'name',
        },
        {
            title: formatMessage({ id: 'app.base.file_url' }),
            dataIndex: 'file_url',
            hideInSearch: true,
            render: (value, record) => (
                <img src={record.file_url} width='130px' onClick={() => {
                    setPreviewImg(record.file_url)
                    handlePreviewModalVisible(true )
                }} />
            )
        },
        {
            title: formatMessage({ id: 'app.base.rank_num' }),
            dataIndex: 'rank_num',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.updated_at' }),
            dataIndex: 'updated_at',
            hideInSearch: true,
            valueType: 'dateTime',
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                <a
                    onClick={() => {
                        handleDataModalVisible(true);
                        setDataFormValues(record);
                        setIsUpdate(true);
                    }}
                >
                    {formatMessage({ id: 'app.base.update' })}
                </a>
                </>
            ),
        },
    ];

    // 请求接口数据, 设置组件状态
    const getTableData = (params:any) => {
        return queryRule(params).then((res:any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }

    // 表单提交
    const handleSubmitDataForm = (value:any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }


    return (
        <PageHeaderWrapper>
          <ProTable<TableListItem>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            toolBarRender={(action, { selectedRows }) => [
              selectedRows && selectedRows.length > 0 && (
                  <Dropdown
                      overlay={
                        <Menu
                            onClick={async e => {
                                if (e.key === 'remove') {
                                    TsxHelper.showDeleteConfirm(
                                        'danger',
                                        handleRemove,
                                        selectedRows,
                                        () => {
                                            setRowKeys([]);
                                            action.reload();
                                        }
                                    )
                                }
                            }}
                            selectedKeys={[]}
                        >
                          <Menu.Item key="remove">
                              {formatMessage({ id: 'app.base.batch_delete' })}
                          </Menu.Item>
                        </Menu>
                      }
                  >
                    <Button>
                        {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                    </Button>
                  </Dropdown>
              ),
              // @ts-ignore
              <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); handleDataModalVisible(true);}}>
                {formatMessage({ id: 'app.base.create' })}
              </Button>,
          ]}
            tableAlertRender={(selectedRowKeys, selectedRows) => (
              <div>
                  {formatMessage({ id: 'app.base.has_select' })}
                <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a>
                  {formatMessage({ id: 'app.base.item'})}&nbsp;&nbsp;
              </div>
          )}
            request={params => getTableData(params)}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                  setRowKeys(selectedRowKeys);
              },
              selectedRowKeys: rowKeys,
          }}
            />
            <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={apiState.common || {}}
                onSubmit={ async formValue => handleSubmitDataForm(formValue) }
                onCancel={() => handleDataModalVisible(false)}
            />
              {
                  previewModelVisible && (
                      <PreviewForm
                          previewModelVisible={previewModelVisible}
                          onVisibleModel={handlePreviewModalVisible}
                          previewImg={previewImg}
                      />
                  )
              }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows.map(row => row.id).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};


export default Form.create<TableListProps>()(TableList);
